import 'package:flutter/material.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:flutter_trip/dao/home_dao.dart';
import 'package:flutter_trip/model/sales_box_model.dart';
import 'package:flutter_trip/page/search_page.dart';
import 'package:flutter_trip/page/speak_page.dart';
import 'package:flutter_trip/widget/grid_nav.dart';
import 'package:flutter_trip/widget/loading_container.dart';
import 'package:flutter_trip/widget/local_nav.dart';
import 'package:flutter_trip/widget/sales_box.dart';
import 'package:flutter_trip/widget/sub_nav.dart';
import 'package:flutter_splash_screen/flutter_splash_screen.dart';

import '../model/common_model.dart';
import '../model/grid_nav_model.dart';
import '../model/home_model.dart';
import '../widget/search_bar.dart';
import '../widget/webview.dart';

const searchBarDefaultText = '网红打卡地 景点 酒店 美食';
const int appbarScrollOffset = 80;

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double _opacity = 0;
  List<CommonModel> localNavList = [];
  List<CommonModel> bannerList = [];
  GridNavModel? gridNav;
  List<CommonModel> subNavList = [];
  SalesBoxModel? salesBox;
  bool _loading = true;

  void _onScroll(double offset) {
    double alpha = offset / appbarScrollOffset;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      _opacity = alpha;
    });
    print("_opacity: $_opacity");
  }

  @override
  void initState() {
    print("initState");
    super.initState();
    _loadData();
    hideScreen();
  }

  Future<void> hideScreen() async {
    Future.delayed(const Duration(milliseconds: 600), () {
      FlutterSplashScreen.hide();
    });
  }

  Future<void> _loadData() async {
    try {
      HomeModel model = await HomeDao.fetch();
      print("model: ${model.toJson().toString()}");
      setState(() {
        if (model.bannerList != null) {
          bannerList = model.bannerList!;
        }
        if (model.localNavList != null) {
          localNavList = model.localNavList!;
        }
        if (model.gridNav != null) {
          gridNav = model.gridNav!;
        }

        if (model.subNavList != null) {
          subNavList = model.subNavList!;
        }

        if (model.salesBox != null) {
          salesBox = model.salesBox;
        }
        _loading = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFf2f2f2),
      body: LoadingContainer(
          isLoading: _loading,
          child: Stack(
            children: [
              MediaQuery.removePadding(
                context: context,
                removeTop: true,
                child: RefreshIndicator(
                  onRefresh: _loadData,
                  child: NotificationListener(
                    onNotification: (scrollNotification) {
                      if (scrollNotification is ScrollUpdateNotification &&
                          scrollNotification.depth == 0) {
                        _onScroll(scrollNotification.metrics.pixels);
                      }
                      return false;
                    },
                    child: _listView,
                  ),
                ),
              ),
              _appBar,
            ],
          )),
    );
  }

  Widget get _listView {
    return ListView(
      children: [
        _banner,
        Padding(
          padding: const EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: LocalNav(localNavList: localNavList),
        ),
        Padding(
          padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: GridNav(gridNavModel: gridNav),
        ),
        Padding(
          padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SubNav(subNavList: subNavList),
        ),
        Padding(
          padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SalesBox(salesBox: salesBox),
        ),
      ],
    );
  }

  Widget get _appBar {
    return Column(
      children: [
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
            padding: const EdgeInsets.only(top: 24),
            height: 80,
            decoration: BoxDecoration(
              color: Color.fromARGB((_opacity * 255).toInt(), 255, 255, 255),
            ),
            child: CustomSearchBar(
              searchBarType:
                  _opacity > 0.2 ? SearchBarType.homeLight : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: searchBarDefaultText,
              leftButtonClick: () {},
            ),
          ),
        ),
      ],
    );
  }

  _jumpToSearch() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return const SearchPage(
        hint: searchBarDefaultText,
      );
    }));
  }

  _jumpToSpeak() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return const SpeakPage();
    }));
  }

  Widget get _banner {
    return SizedBox(
      height: 160,
      child: Swiper(
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return WebView(
                  url: bannerList[index].url!,
                );
              }));
            },
            child: Image.network(
              bannerList[index].icon!,
              fit: BoxFit.fill,
            ),
          );
        },
        autoplay: true,
        itemCount: bannerList.length,
        pagination: const SwiperPagination(),
        //control: const SwiperControl(),
      ),
    );
  }
}
